﻿using System;
using System.Collections.Generic;
using System.Windows.Forms;
using System.Runtime.InteropServices;

namespace Scan
{
    static class Program
    {
        [DllImport("coredll.dll", EntryPoint = "CreateMutex", SetLastError = true)]
        public static extern IntPtr CreateMutex(IntPtr lpMutexAttributes, bool bInitiaOwner, string lpName);
        [DllImport("coredll.dll", SetLastError = true)]
        public static extern int ReleaseMutex(IntPtr hMutex);
        [DllImport("coredll.dll", CharSet = CharSet.Unicode, SetLastError = true)]
        public static extern IntPtr FindWindow(string lpClassName, string lpWindowName);
        [DllImport("coredll.dll", CharSet = CharSet.Unicode, SetLastError = true)]
        public static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);
        [DllImport("coredll.dll")]
        private static extern bool SetForegroundWindow(IntPtr hWnd); 
        public const int ERROR_ALREADY_EXISTS = 183;
        public const int SW_SHOW = 5;
        public static frmMain MainWindow;

        /// <summary>
        /// 应用程序的主入口点。
        /// </summary>
        [MTAThread]
        static void Main()
        {

            IntPtr hMutex = CreateMutex(IntPtr.Zero, false, @"Scan"); 
            if (Marshal.GetLastWin32Error() == ERROR_ALREADY_EXISTS) 
            {
                IntPtr mainFrm = FindWindow(null, edit_config.ConfigGetValue("TitleName"));
                ShowWindow(mainFrm, SW_SHOW); 
                SetForegroundWindow(mainFrm); 
                Application.Exit();
            }
            else
            { 
                MainWindow = new frmMain();
                Application.Run(MainWindow); 
                ReleaseMutex(hMutex); 
            }
        }
    }
}